<template>
  <div class="MyProduct">
    <MyHeader>
      <span>我的商品</span>
    </MyHeader>
    <div class="MyProductContent">
      <el-table
        :data="tableObj.temporary"
        @row-click="handleRow"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="index" label="序号" width="100">
        </el-table-column>

        <el-table-column prop="imgPath" label="图片" width="150">
          <template slot-scope="scope">
            <img
              :src="require('/src/assets/img/' + scope.row.imgPath)"
              width="50"
              height="50"
            />
          </template>
        </el-table-column>

        <el-table-column prop="name" label="产品名称" width="120">
        </el-table-column>

        <el-table-column prop="type" label="类型" width="120">
        </el-table-column>

        <el-table-column prop="brand" label="品牌" width="120">
        </el-table-column>

        <el-table-column prop="price" label="价格" width="150">
        </el-table-column>

        <el-table-column prop="store" label="库存量" width="120">
        </el-table-column>

        <el-table-column prop="" label="相关操作" width="300">
          <el-button
            type="success"
            icon="el-icon-circle-plus-outline"
            @click="addStore"
            >添加库存</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-circle-plus-outline"
            @click="delProduct"
            >下架商品</el-button
          >
        </el-table-column>
      </el-table>
      <div class="btnDiv">
        <el-button @click="addNewProduct" type="success" round
          >新添商品</el-button
        >
      </div>

      <!-- 添加商品库存弹出框 -->
      <el-dialog
        title="请输入要添加的商品数量"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-input
          placeholder="商品数量"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          v-model="store"
          clearable
          type="text"
        >
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="
              dialogVisible = false;
              isAdd = false;
              isDel = false;
              isStore = false;
            "
            >取 消</el-button
          >
          <el-button type="primary" @click="confirmAddStore">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加新商品弹出框 -->
      <el-dialog
        title="添加新商品"
        :visible.sync="dialogVisibleProduct"
        width="30%"
        :before-close="handleClose"
      >
        <!-- 表单 -->
        <el-form
          status-icon
          :rules="rules"
          :model="newTeaForm"
          ref="newTeaForm"
          style="color: black"
        >
          <el-form-item label="茶名" name="" label-width="70px" prop="name">
            <el-input type="text" v-model="newTeaForm.name" />
          </el-form-item>
          <el-form-item label="类型" name="" label-width="70px" prop="">
            <el-select v-model="newTeaForm.type">
              <el-option value="红茶">红茶</el-option>
              <el-option value="绿茶">绿茶</el-option>
              <el-option value="白茶">白茶</el-option>
              <el-option value="乌龙茶">乌龙茶</el-option>
              <el-option value="黑茶">黑茶</el-option>
              <el-option value="黄茶">黄茶</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="品牌" name="" label-width="70px" prop="brand">
            <el-input type="text" v-model="newTeaForm.brand" />
          </el-form-item>
          <el-form-item label="价格" name="" label-width="70px" prop="price">
            <el-input
              onkeyup="value=value.replace(/[^\d]/g,'')"
              type="text"
              v-model="newTeaForm.price"
            />
          </el-form-item>
          <el-form-item label="茶厂" name="" label-width="70px" prop="industry">
            <el-input type="text" v-model="newTeaForm.industry" />
          </el-form-item>
          <el-form-item label="库存量" name="" label-width="70px" prop="store">
            <el-input
              onkeyup="value=value.replace(/[^\d]/g,'')"
              type="text"
              v-model="newTeaForm.store"
            />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button
            @click="
              dialogVisibleProduct = false;
              isAdd = false;
              isDel = false;
              isStore = false;
            "
            >取 消</el-button
          >
          <el-button type="primary" @click="confirmAdd('newTeaForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 支付密码弹出框 -->
      <el-dialog
        title="请输入支付密码"
        :visible.sync="dialogVisiblePwd"
        width="30%"
      >
        <el-input
          placeholder="支付密码"
          v-model="payPassword"
          clearable
          type="password"
        >
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="
              dialogVisiblePwd = false;
              isAdd = false;
              isDel = false;
              isStore = false;
            "
            >取 消</el-button
          >
          <el-button type="primary" @click="Payment">确 定</el-button>
        </span>
      </el-dialog>
      <Pages :tableObjs="tableObj"></Pages>
      <h3 style="color: red">我的茶叶销售情况</h3>
      <div class="MyProductContent"><MySaleCondition></MySaleCondition></div>
      <div class="MyProductContent"><SaleCon></SaleCon></div>
    </div>
  </div>
</template>

<script>
// import axios from 'axios'
import { getRequest } from "../../util/tools";
import { getReq } from "../../util/request";
import MyHeader from "../../components/MyHeader.vue";
import Pages from "../../components/Pages.vue";
import SaleCon from "../../components/MyCenter/SaleCon.vue";
import MySaleCondition from "../../components/MyCenter/MySaleCondition.vue";
import axios from "axios";
export default {
  name: "MyProduct",
  components: {
    MyHeader,
    Pages,
    SaleCon,
    MySaleCondition,
  },
  data() {
    return {
      tableObj: {
        tableData: [],
        number: 2,
        totalPages: 0,
        currentPage: 1,
        temporary: [],
      },
      userId: "",
      rowData: "",
      dialogVisible: false,
      dialogVisiblePwd: false,
      dialogVisibleProduct: false,
      payPassword: "",
      store: "",
      isStore: false,
      isDel: false,
      isAdd: false,
      newTeaForm: {
        name: "",
        type: "红茶",
        brand: "",
        price: "",
        industry: "",
        store: "",
      },

      //验证规则匹配
      rules: {
        //验证用户名
        name: [
          {
            validator: (rule, value, callback) => {
              if (value.trim() === "") {
                callback(new Error("输入不能为空！"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        //品牌
        brand: [
          {
            validator: (rule, value, callback) => {
              if (value.trim() === "") {
                callback(new Error("输入不能为空！"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        //价格
        price: [
          {
            validator: (rule, value, callback) => {
              if (value.trim() === "") {
                callback(new Error("输入不能为空！"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        //茶厂
        industry: [
          {
            validator: (rule, value, callback) => {
              if (value.trim() === "") {
                callback(new Error("输入不能为空！"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        //库存量
        store: [
          {
            validator: (rule, value, callback) => {
              if (value.trim() === "") {
                callback(new Error("输入不能为空！"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    handleRow(row) {
      // console.log(row)
      if (this.rowData !== "") {
        this.rowData = "";
      }
      this.rowData = row;
      // console.log(row)
    },
    //添加库存弹出框
    addStore() {
      this.dialogVisible = true;
    },
    // 添加商品库存
    confirmAddStore() {
      this.isStore = true;
      this.isDel = false;
      this.isAdd = false;
      this.dialogVisiblePwd = true;
    },
    //添加新商品
    confirmAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isStore = false;
          this.isDel = false;
          this.isAdd = true;
          this.dialogVisiblePwd = true;
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },

    //添加商品
    addNewProduct() {
      this.dialogVisibleProduct = true;
    },

    //下架商品
    delProduct() {
      setTimeout(() => {
        if (window.confirm("确定要移除商品吗？")) {
          this.dialogVisiblePwd = true;
          this.isDel = true;
          this.isAdd = false;
          this.isStore = false;
        }
      }, 0);
    },

    //输入支付密码
    Payment() {
      const p = new Promise((resolve, reject) => {
        axios
          .get(
            `http://localhost:3000/user/getUserPaypwd?userId=${this.userId}&paypwd=${this.payPassword}`
          )
          .then(
            (response) => resolve(response),
            (error) => {
              reject(error);
            }
          );
      });
      p.then(
        (response) => {
          console.log(
            "response.data.pwdIsRight",
            response.data.pwdIsRight,
            this.isStore,
            this.isDel,
            this.isAdd
          );
          // console.log('this.rowData.teaId',this.rowData.teaId)
          if (response.data.pwdIsRight) {
            if (this.isStore) {
              axios
                .post("http://localhost:3000/user/updateStore", {
                  store: this.store,
                  teaId: this.rowData.teaId,
                })
                .then(
                  (response) => {
                    this.$message({
                      message: response.data.msg,
                      type: "success",
                    });
                    getRequest(
                      `http://localhost:3000/user/getUserProducts?userId=${this.userId}`,
                      this.tableObj
                    );
                  },
                  (error) => {
                    console.log(error);
                  }
                );
              this.dialogVisible = false;
              this.dialogVisiblePwd = false;
              this.store = "";
              this.payPassword = "";
              this.isStore = false;
            } else if (this.isDel) {
              axios
                .post("http://localhost:3000/user/delTea", {
                  teaId: this.rowData.teaId,
                })
                .then((response) => {
                  this.$message({
                    message: response.data.msg,
                    type: "success",
                  });
                  getRequest(
                    `http://localhost:3000/user/getUserProducts?userId=${this.userId}`,
                    this.tableObj
                  );
                  this.dialogVisible = false;
                  this.dialogVisiblePwd = false;
                  this.store = "";
                  this.payPassword = "";
                  this.isDel = false;
                  // console.log(response)
                });
            } else if (this.isAdd) {
              //先判断数据库中有没有这种茶叶
              // console.log(this.newTeaForm)
              const p = new Promise((resolve, reject) => [
                axios
                  .post("http://localhost:3000/user/addNewTea", {
                    newTea: this.newTeaForm,
                    userId: this.userId,
                  })
                  .then(
                    (response) => resolve(response),
                    (error) => {
                      reject(error);
                    }
                  ),
              ]);
              p.then(
                (response) => {
                  //要添加的商品已经存在，不让添加
                  if (response.data.isAdded) {
                    this.$message({
                      message: response.data.msg,
                      type: "warning",
                    });
                    (this.newTeaForm.name = ""),
                      (this.newTeaForm.type = ""),
                      (this.newTeaForm.brand = ""),
                      (this.newTeaForm.industry = ""),
                      (this.newTeaForm.price = ""),
                      (this.newTeaForm.store = "");
                  } else {
                    this.$message({
                      message: response.data.msg,
                      type: "success",
                    });
                    getRequest(
                      `http://localhost:3000/user/getUserProducts?userId=${this.userId}`,
                      this.tableObj
                    );
                    this.dialogVisibleProduct = false;
                    this.dialogVisiblePwd = false;
                    this.payPassword = "";
                    this.isAdd = false;
                    (this.newTeaForm.name = ""),
                      (this.newTeaForm.type = ""),
                      (this.newTeaForm.brand = ""),
                      (this.newTeaForm.industry = ""),
                      (this.newTeaForm.price = ""),
                      (this.newTeaForm.store = "");
                  }
                },
                (error) => {
                  console.log(error);
                }
              );
            }
          } else {
            this.$message.error("密码输入错误,请重新操作！");
            this.payPassword = "";
          }
        },
        (error) => {
          console.log(error);
        }
      );
    },
    //关闭弹出层
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.store = "";
          this.isStore = false;
          this.isAdd = false;
          this.isDel = false;
          done();
        })
        .catch(() => {});
    },

    //初始化
    init() {
      getRequest(
        `http://localhost:3000/user/getUserProducts?userId=${this.userId}`,
        this.tableObj
      );
    },

    //获取商品库存
    getStore() {
      let getResult = getReq("order/selTeaStore", `?userId=${this.userId}`);
      getResult.then(
        (response) => {
          this.$message({
            showClose: true,
            message:
              "您的商品   " +
              response.data.map((item) => {
                return item.name;
              }) +
              "   库存快不足了！快去添加库存吧！",
            type: "warning",
            duration: 5000,
          });
        },
        (err) => {
          throw err;
        }
      );
    },
  },
  mounted() {
    this.userId = this.$cookie.get("userId");
    this.init();
    this.getStore();
    this.$bus.$on("modify", (data) => {
      if (data) {
        this.init();
      }
    });
  },
  beforeDestroy() {
    this.$bus.$off("modify");
  },
};
</script>

<style scoped lang='less'>
.MyProduct {
  width: 100%;
  min-height: 900px;
  background-color: white;
  .MyProductContent {
    width: 98%;
    margin-left: 10px;
    min-height: 500px;
    .btnDiv {
      width: 100%;
      height: 80px;
      line-height: 80px;
      button {
        float: left;
        margin-left: 20px;
        margin-top: 30px;
        // color:rgb(255, 0, 0)
      }
    }
  }
}
</style>